package cn.easy.mortgage.config;

import cn.easy.mortgage.utils.Constants;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 公众号过滤器
 */
@Component
public class WxMpAuthFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private String excludeUrls = "";
    private WxMpService wxMpService;
    private PathMatcher pathMatcher = new AntPathMatcher();

    public WxMpAuthFilter() {
    }

    public WxMpAuthFilter(WxMpService wxMpService) {
        this.wxMpService = wxMpService;
    }

    public void init(FilterConfig fConfig) throws ServletException {
        excludeUrls = fConfig.getInitParameter("excludeUrls");
        logger.info("WxMpAuthFilter init");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String channel = req.getParameter(Constants.CHANNEL_CODE);
        if (StringUtils.isNotBlank(channel)) {
            req.getSession().setAttribute(Constants.CHANNEL_CODE, channel);
        }

        chain.doFilter(request, response);
    }


    private boolean isContains(String excludeUrls, String url) {
        List<String> excludeUrlList = Arrays.asList(excludeUrls.split(","));
        for (String excludeUrl : excludeUrlList) {
            if (pathMatcher.match(excludeUrl, url)) {
                return true;
            }
        }
        return false;
    }

    public void destroy() {
        logger.info("WxMpAuthFilter destroy");
    }

}
